/*
 * @Author: 橘子
 * @Date: 2021-10-08 21:30:09
 * @Project_description: 按钮
 * @Description: 代码是我抄的，不会也是真的
 */
'use strict'
import { supPath } from '@/menu/formatRoute'
import { addRoutes, filterRoute } from '@/menu/filterAsyncRouter'
import db from '@/libs/utli.dbPlus'
import store from '@/store'
import { frameInRoutes } from '@/router/routes'
import { cloneDeep } from 'lodash'
import devRouter from '@/router/system/devRouter'
import { errorPage } from '@/router/system/sysRouter'
import api from '@/api/index'
import util from '@/libs/util'

/**
 * 设置全局顶部菜单栏
 * @param route 接口返回的路由list
 */
export function setGlobalMenuHeader(route = []) {
  //储存路由为本地，方便读取
  db._setGlobalDb('menuHeader', route)
  // sort一下
  let routeList = deepSortMenu(cloneDeep(route))
  //遍历后台传来的路由，转换为组件对象
  let list = filterRoute(routeList)
  //添加到动态路由 TODO：顶部路由其实不用添加
  // addRoutes(list)
  list.unshift(...devRouter)
  //处理路由为d2认识的路由
  let storeRouter = supPath(cloneDeep(list))
  // 设置顶栏菜单
  store.commit('d2admin/menu/headerSet', storeRouter)
}

/**
 * 设置全局侧边菜单
 * @param route 接口返回的路由list
 */
export function setGlobalMenuAside(route = []) {
 
  let routeList = cloneDeep(route)
  let list = filterRoute(routeList)
  // return
  list.unshift(...frameInRoutes)
  list.push(...errorPage)
  //添加到动态路由
  addRoutes(list)
  //储存路由为本地，方便读取
  db._setGlobalDb('menuAside', list)
  // 可以作为头部标签
  store.commit('d2admin/page/init', list)
  //处理路由为d2认识的路由
  let storeRouter = supPath(cloneDeep(list))
  // 设置侧边栏菜单
  store.commit('d2admin/menu/asideSet', storeRouter)
}

/**
 * 获取用户路由,并且渲染路由
 * @param id 账号id
 */
export async function getUserMenu(id) {
  try {
    // let { data } = await api.menu.userTree(id)
    // try{
    //   //获取用户组织id防止刷新后查询的id为空
    //   //id为1的是超级管理员
    //   //id为2的是系统管理员
    //   if(id!=1&&id!=2){

    //     // 储存orgId
    //     let userId = util.cookies.get('userId')

    //     let org = await api.org.list({userId})
    //     let orgId = org.data.rows[0].id
    //     await store.dispatch('d2admin/user/setOrgId', orgId)
    //   }

    // }catch (e) {

    // }
    let data = []
    let menu = deepSortMenu(cloneDeep(data))
    setGlobalMenuAside(menu)
    setGlobalMenuHeader()
    return menu
  } catch (e) {
    console.log(e)
    return []
  }
}

/**
 * 深度Sort按钮
 * @param arr
 */
export const deepSortMenu = function (arr) {
  arr.sort((a, b) => {
    return a.sort - b.sort
  })
  arr.forEach((item) => {
    if (item.children) {
      deepSortMenu(item.children)
    }
  })
  return arr
}
